package com.maple.phoneward.custom;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import android.content.Context;

import com.maple.phoneward.activity.R;
import com.maple.phoneward.utils.FileUtil;

/**
 * EmailSender.java
 * 
 * @author YaJian Qiu
 * @time 2013-3-27 下午8:00:56<br>
 *       本类描述：发送邮件的工具类
 * 
 */
public class EmailSender {
	private Properties properties;
	private Session session;
	private Message message;
	private MimeMultipart multipart;
	private Context context;
	private String appName;

	public EmailSender(Context context) {
		this.context = context;
		this.appName = context.getString(R.string.app_name);
		this.properties = new Properties();
	}

	public void setProperties(String host, String post) {
		// 地址
		this.properties.put("mail.smtp.host", host);
		// 端口号
		this.properties.put("mail.smtp.post", post);
		// 是否验证
		this.properties.put("mail.smtp.auth", true);
		this.session = Session.getInstance(properties);
		this.message = new MimeMessage(session);
		this.multipart = new MimeMultipart("mixed");
	}

	/**
	 * 设置收件人
	 * 
	 * @param receivers
	 * @throws MessagingException
	 */
	public void setReceiver(String... receivers) throws MessagingException {
		Address[] address = new InternetAddress[receivers.length];
		for (int i = 0; i < receivers.length; i++) {
			address[i] = new InternetAddress(receivers[i]);
		}
		this.message.setRecipients(Message.RecipientType.TO, address);
	}

	/**
	 * 设置邮件
	 * 
	 * @param from
	 *            来源
	 * @param title
	 *            标题
	 * @param content
	 *            内容
	 * @throws AddressException
	 * @throws MessagingException
	 */
	public void setMessage(String from, String title, String content) throws AddressException, MessagingException {
		String nick = "";//昵称
		try {
			nick = MimeUtility.encodeText(appName);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		this.message.setFrom(new InternetAddress(nick + " <" + from + ">"));
		this.message.setSubject(title);
		// 纯文本的话用setText()就行，不过有附件就显示不出来内容了
		MimeBodyPart textBody = new MimeBodyPart();
		content = String.format(FileUtil.getStringFromAssets(context, "emailTemplate.txt"), content);//将内容填充到模版中
		textBody.setContent(content, "text/html;charset=UTF-8");
		this.multipart.addBodyPart(textBody);
	}

	/**
	 * 添加附件
	 * 
	 * @param filePath
	 *            文件路径
	 * @throws MessagingException
	 */
	public void addAttachment(String filePath) throws MessagingException {
		FileDataSource fileDataSource = new FileDataSource(new File(filePath));
		DataHandler dataHandler = new DataHandler(fileDataSource);
		MimeBodyPart mimeBodyPart = new MimeBodyPart();
		mimeBodyPart.setDataHandler(dataHandler);
		try {
			mimeBodyPart.setFileName(MimeUtility.encodeText(fileDataSource.getName()));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		this.multipart.addBodyPart(mimeBodyPart);
	}

	/**
	 * 发送邮件
	 * 
	 * @param host
	 *            地址
	 * @param account
	 *            账户名
	 * @param pwd
	 *            密码
	 * @throws MessagingException
	 */
	public void sendEmail(String host, String account, String pwd) throws MessagingException {
		// 发送时间
		this.message.setSentDate(new Date());
		// 发送的内容，文本和附件
		this.message.setContent(this.multipart);
		this.message.saveChanges();
		// 创建邮件发送对象，并指定其使用SMTP协议发送邮件
		Transport transport = session.getTransport("smtp");
		// 登录邮箱
		transport.connect(host, account, pwd);
		// 发送邮件
		transport.sendMessage(message, message.getAllRecipients());
		// 关闭连接
		transport.close();
	}
}
